package com.jh.user.controller;


import cn.jh.common.exception.ServiceException;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.TokenUtil;
import com.jh.user.business.*;
import com.jh.user.pojo.*;
import com.jh.user.pojo.enums.ThirdPayType;
import com.jh.user.repository.FastSilverPicPathRepository;
import com.jh.user.service.PlatformService;
import com.jh.user.util.CommonsUtil;
import com.jh.user.util.CompressUtil;
import com.jh.user.util.QRCodeUtil;
import com.jh.user.util.Util;
import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
public class PlatformController {

    //二维码内容,前端h5地址
    @Value("${platform.contents}")
    private String contents;

    //二维码生成保存路径
    @Value("${platform.outPutPath}")
    private String outPutPath;

    //二维码生成保存路径
    @Value("${platform.uploadpath}")
    private String uploadpath;

    /**
     * 二维码临时目录
     */
    @Value("${platform.qrcodePath}")
    private String qrcodePath;

    /**
     * zip包现在地址
     */
    @Value("${platform.downloadpath}")
    private String downloadpath;

    //二维码生成格式
    @Value("${platform.imageType}")
    private String imageType;

    //二维码宽度
    @Value("${platform.width}")
    private String width;

    //二维码高度
    @Value("${platform.height}")
    private String height;

    //生成台卡前三位
    private final String front = "188";

    private final ThirdPayRateBusiness thirdPayRateBusiness;
    private final PlatformService platformService;
    private final ShopRegisterBussiness shopRegisterBussiness;
    private final UserLoginRegisterBusiness userLoginRegisterBusiness;
    private final UserRoleResourceBusiness userRoleResourceBusiness;
    private final UserBankInfoBusiness userBankInfoBusiness;
    private final FastSilverPicPathRepository fastSilverPicPathRepository;
    private final RestTemplate restTemplate;
    private final Util util;

    @Autowired
    public PlatformController(ThirdPayRateBusiness thirdPayRateBusiness,
                              PlatformService platformService,
                              ShopRegisterBussiness shopRegisterBussiness,
                              UserLoginRegisterBusiness userLoginRegisterBusiness,
                              UserRoleResourceBusiness userRoleResourceBusiness,
                              UserBankInfoBusiness userBankInfoBusiness,
                              FastSilverPicPathRepository fastSilverPicPathRepository,
                              RestTemplate restTemplate,
                              Util util) {
        this.thirdPayRateBusiness = thirdPayRateBusiness;
        this.platformService = platformService;
        this.shopRegisterBussiness = shopRegisterBussiness;
        this.userLoginRegisterBusiness = userLoginRegisterBusiness;
        this.userRoleResourceBusiness = userRoleResourceBusiness;
        this.userBankInfoBusiness = userBankInfoBusiness;
        this.fastSilverPicPathRepository = fastSilverPicPathRepository;
        this.restTemplate = restTemplate;
        this.util = util;
    }

    private static Logger log = LoggerFactory.getLogger(PlatformController.class);

    /**
     * 批量生成台卡
     */
    @RequestMapping(method = RequestMethod.POST, value = ("/v1.0/user/app/Platform/savePlatform/{token}"))
    public @ResponseBody
    Object savePlatform(@PathVariable("token") String token, Platform platform, @RequestParam(value = "type", required = false) String type,
                        @RequestParam(value = "platformNumber", required = false) Integer platformNumber
    ) {
        Map param = new HashMap();
        String number = platformService.selectPlatform(platform);
        long userId = 0;
        try {
            userId = TokenUtil.getUserId(token);
            param = addQRCode(number, platform, type, platformNumber);
        } catch (Exception e) {
            log.error("PlatformSevice.savePlatform，新增台卡userId=====" + userId + ",异常=", e);
            return CommonsUtil.returnError("新增台卡失败!");
        }
        return CommonsUtil.returnSuccess(param);
    }

    public Map addQRCode(String number, Platform platform, String type, Integer platformNumber) throws Exception {
        Map param = new HashMap();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");

        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String times = sd.format(date);
        String dateNo = sdf.format(date);
        String time = "";

        //台卡号16位
        if (StringUtils.isBlank(number)) {
            number = dateNo + "0000000";
            number = number.substring(number.length() - 8);
        } else {
            time = number.substring(3, 9);
            number = number.substring(number.length() - 8);
            int timeCount = compareDate(time, dateNo);
            if (timeCount < 1) {
                dateNo = time;
            }
        }
        int count = 0;
        int end = 0;
        int start = 0;
        int num = Integer.valueOf(number);
        dateNo = dateNo.substring(0, dateNo.length() - 1);
        List<Platform> list = new ArrayList<>();
        for (int i = 0; i < platformNumber; i++) {
            num++;
            //type=1:save接口生成二维码，2：生成顺序；
            if (type.equalsIgnoreCase("1")) {
                String platformCode = front + dateNo + num;
                String outPath = outPutPath + platformCode + "." + imageType;
                param.put("platformCode", platformCode);
                param.put("contents", contents + "?platformCode=" + front + dateNo + num);
                param.put("width", width);
                param.put("height", height);
                param.put("outPutPath", outPath);
                param.put("imageType", imageType);
                Platform platform1 = new Platform();
                //生成二维码
                QRCodeUtil.AddQRCode(param);
                platform1.setPlatformId(platformCode);
                platform1.setQrcCode(uploadpath + platformCode + "." + imageType);
                platform1.setUpdateTime(times);
                platform1.setPlatformCode(platformCode);
                platform1.setPlatformType(platform.getPlatformType());
                platform1.setDialCodeType("0");
                platform1.setUpdateBy("system");
                platform1.setCreateBy("system");
                platform1.setState("0");
                list.add(platform1);
            } else {
                if (count == 0) {
                    start = num;
                }
                count++;
                end = num;
            }
        }

        if (type.equalsIgnoreCase("2")) {
            param.put("startNumber", front + dateNo + start);
            param.put("endNumber", front + dateNo + end);
        } else {
            platformService.addPlatform(list);
        }
        return param;
    }

    private int compareDate(String start, String end) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
        Date startTime = df.parse(start);
        Date endTime = df.parse(end);
        if (startTime.getTime() < endTime.getTime()) {
            return 1;
        } else if (startTime.getTime() > endTime.getTime()) {
            return 2;
        } else {
            return 0;
        }
    }

    /**
     * 批量拨码
     */
    @RequestMapping(method = RequestMethod.POST, value = ("/v1.0/user/app/Platform/batchDialCode/{token}"))
    @ResponseBody
    public Object batchDialCode(@PathVariable("token") String token, PlatformEntity entity) {
        String[] dialCodes = entity.getDialCode().split(",");
        Platform platform = new Platform();
        long userId = 0;
        try {
            TokenUtil.getUserId(token);
            int count = platformService.queryAgent(entity.getAgent());
            if (count < 1) {
                return CommonsUtil.returnError("代理商不存在，请确认！");
            }
            for (int i = 0; i < dialCodes.length; i++) {
                String platformCode = dialCodes[i];
                platform.setPlatformCode(platformCode);
                //判断agent角色
                String agent = entity.getAgent();
                long roleId = userLoginRegisterBusiness.findRoleByPhone(agent);
                if (roleId != 6) {
                    log.info(agent + "用户不是台卡代理角色，无法拨码！");
                    continue;
                }
                platform.setAgent(entity.getAgent());
                platform.setDialCodeType("1");
                platformService.updatePlatform(platform, "2");
            }
            return CommonsUtil.returnSuccess(null);
        } catch (Exception e) {
            log.error("PlatformController.batchDialCode,批量拨码userId=====" + userId + ",异常=======", e);
            return CommonsUtil.returnError("批量拨码绑定商户失败！");
        }
    }

    /**
     * app端/OEM/总后台查询台卡列表
     */
    @RequestMapping(method = RequestMethod.GET, value = ("/v1.0/user/app/Platform/queryPlatform/{token}"))
    @ResponseBody
    public Object queryPlatformList(@PathVariable("token") String token, PlatformEntity entity) {
        List<Platform> list;
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return CommonsUtil.returnError("token无效！");
        }
        try {
            String merchantId = entity.getMerchantId();
            String agent = entity.getAgent();
            String platformCode = entity.getPlatformCode();
            if (StringUtils.isNotEmpty(merchantId) && StringUtils.isEmpty(agent) && StringUtils.isEmpty(platformCode)) {
                // app第一步
                list = platformService.queryPlatform(entity);
                if(null != list && list.size() > 0) {
                    for(Platform platform : list ) {
                        ShopRegister shopRegister = shopRegisterBussiness.findByUserId(userId);
                        if(shopRegister != null) {
                            platform.setShopName(StringUtils.isBlank(shopRegister.getShopName()) ? "" : shopRegister.getShopName());
                        }
                    }
                }
            } else if (StringUtils.isEmpty(merchantId) && StringUtils.isEmpty(agent) && StringUtils.isNotEmpty(platformCode)) {
                // app第二步
                list = platformService.queryPlatform(entity);
                if (null == list || list.size() == 0) {
                    return CommonsUtil.returnError("无该台卡信息！");
                }
            } else {
                // OEM
                list = platformService.queryPlatform(entity);
                if(null != list && list.size() > 0) {
                    User user = userLoginRegisterBusiness.queryUserByPhone(agent);
                    if (null == user) {
                        return CommonsUtil.returnError("无该台卡代理用户信息！");
                    }
                    for(Platform platform : list) {
                        // 查询台卡代理下的商铺信息
                        String shopId = platform.getShopId();
                        if (StringUtils.isNotEmpty(shopId)) {
                            ShopRegister shopRegister = shopRegisterBussiness.findByMobilePhone(shopId);
                            if(shopRegister != null) {
                                platform.setShopName(StringUtils.isBlank(shopRegister.getShopName()) ? "" : shopRegister.getShopName());
                            }
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("查询台卡列表失败！");
        }
        return CommonsUtil.returnSuccess(list);
    }


    /**
     * 查询台卡分页列表
     */
    @RequestMapping(method = RequestMethod.GET, value = ("/v1.0/user/app/Platform/queryPlatformPagerlist/{token}"))
    @ResponseBody
    public Object queryPlatformPagerlist(@PathVariable("token") String token,
                                         @RequestParam("pageNumber") int pageNumber, PlatformEntity entity
                                         ) {
        if (pageNumber < 1) {
            pageNumber = 1;
        }
        List<Platform> list;
        long userId = 0;
        try {
            userId = TokenUtil.getUserId(token);
            list = platformService.queryPlatformList(pageNumber, entity);
            int count = platformService.queryPlatformCount(entity);
            Map map = new HashMap();
            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESULT, list);
            map.put(CommonConstants.RESP_MESSAGE, "成功");
            map.put("count", count);
            return map;
        } catch (Exception e) {
            log.error("PlatformController.queryPlatformList,查询台卡列表userId=====" + userId + ",异常=", e);
            return CommonsUtil.returnError("查询台卡列表失败！");
        }

    }

    /**
     * 查询台卡信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/app/Platform/query/{token}")
    @ResponseBody
    public Object queryPlatform(@PathVariable("token") String token, @RequestParam("platformCode") String platformCode,
                                @RequestParam("state") String state) {
        long userId = 0;
        try {

            userId = TokenUtil.getUserId(token);
            Platform platform = platformService.findPlatform(platformCode, state);
            if(platform != null){
                ShopRegister shopRegister = shopRegisterBussiness.findByUserId(userId);
                if(shopRegister != null){
                    platform.setShopName(StringUtils.isBlank(shopRegister.getShopName()) ? "" : shopRegister.getShopName());
                }

            }
            return CommonsUtil.returnSuccess(platform);
        } catch (Exception e) {
            log.error("PlatformController.queryPlatform,查询台卡userId=====" + userId + ",异常=", e);
            return CommonsUtil.returnError("查询台卡失败！");
        }
    }

    /**
     * 导出台码信息
     */

    @RequestMapping(method = RequestMethod.POST, value = ("/v1.0/user/app/Platform/export/{token}"))
    @ResponseBody
    public void export(PlatformEntity entity, @PathVariable("token") String token, HttpServletResponse response) {
        List<Platform> list = new ArrayList<>();
        long userId = 0;

        //响应到客户端
        try {
            userId = TokenUtil.getUserId(token);
            if (entity.getArrType().equalsIgnoreCase("0")) {
                //获取数据
                list = platformService.queryPlatform(entity);
            } else {
                if (StringUtils.isNotBlank(entity.getPlatformCode())) {
                    list = platformService.selectPlatform(entity.getPlatformCode());
                }
            }


            String fileName = "台码" + System.currentTimeMillis() + ".xls";
            List<Map<String, Object>> result = new ArrayList<>();
            for (Platform vo : list) {
                Map<String, Object> map = new HashMap();
                map.put("merchantId", StringUtils.isBlank(vo.getShopId()) ? "" : vo.getShopId());
                map.put("platformCode", StringUtils.isBlank(vo.getPlatformCode()) ? "" : vo.getPlatformCode());
                String platformType = StringUtils.isBlank(vo.getPlatformType()) ? "" : vo.getPlatformType();
                if (platformType.equalsIgnoreCase("0")) {
                    platformType = "未拨码";
                } else if (platformType.equalsIgnoreCase("1")) {
                    platformType = "已拨码";
                }
                map.put("platformType", platformType);
                map.put("agent", StringUtils.isBlank(vo.getAgent()) ? "" : vo.getAgent());
                map.put("merchantId", StringUtils.isBlank(vo.getShopId()) ? "" : vo.getShopId());
                String dialCodeType = StringUtils.isBlank(vo.getDialCodeType()) ? "" : vo.getDialCodeType();
                if (dialCodeType.equalsIgnoreCase("0")) {
                    dialCodeType = "未绑定";
                } else if (dialCodeType.equalsIgnoreCase("1")) {
                    dialCodeType = "已绑定";
                } else if (dialCodeType.equalsIgnoreCase("2")) {
                    dialCodeType = "已绑定";
                }
                map.put("dialCodeType", dialCodeType);
                map.put("state", StringUtils.isBlank(vo.getState()) ? "" : vo.getState());
                map.put("createTime", StringUtils.isBlank(vo.getCreateTime()) ? "" : vo.getCreateTime());
                map.put("createBy", StringUtils.isBlank(vo.getCreateTime()) ? "" : vo.getCreateTime());
                result.add(map);
            }

            List<List<Map<String, Object>>> resultList = new ArrayList<>();
            resultList.add(result);

            //创建HSSFWorkbook对象(excel的文档对象)
            HSSFWorkbook wb = new HSSFWorkbook();
            //建立新的sheet对象（excel的表单）
            HSSFSheet sheet = wb.createSheet("台码信息表");
            //在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
            HSSFRow row1 = sheet.createRow(0);
            //创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
            HSSFCell cell = row1.createCell(0);

            // 1.生成字体对象
            HSSFFont font = wb.createFont();
            font.setFontHeightInPoints((short) 12);
            font.setFontName("新宋体");

            // 2.生成样式对象，这里的设置居中样式和版本有关，我用的poi用HSSFCellStyle.ALIGN_CENTER会报错，所以用下面的
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置居中样式
            style.setFont(font); // 调用字体样式对象
            style.setWrapText(true);

            // 3.单元格应用样式
            cell.setCellStyle(style);

            //设置单元格内容
            cell.setCellValue("台卡信息报表");
            //合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));

            //在sheet里创建第二行
            HSSFRow row2 = sheet.createRow(1);
            //创建单元格并设置单元格内容及样式
            HSSFCell cell0 = row2.createCell(0);
            cell0.setCellStyle(style);
            cell0.setCellValue("台卡卡号");

            HSSFCell cell1 = row2.createCell(1);
            cell1.setCellStyle(style);
            cell1.setCellValue("卡片类型");

            HSSFCell cell2 = row2.createCell(2);
            cell2.setCellStyle(style);
            cell2.setCellValue("所属代理商");

            HSSFCell cell3 = row2.createCell(3);
            cell3.setCellStyle(style);
            cell3.setCellValue("拨码状态");

            HSSFCell cell4 = row2.createCell(4);
            cell4.setCellStyle(style);
            cell4.setCellValue("创建时间");

            HSSFCell cell5 = row2.createCell(5);
            cell5.setCellStyle(style);
            cell5.setCellValue("创建人");

            //单元格宽度自适应
            sheet.autoSizeColumn((short) 3);
            sheet.autoSizeColumn((short) 4);
            sheet.autoSizeColumn((short) 5);
            //宽度自适应可自行选择自适应哪一行，这里写在前面的是适应第二行，写在后面的是适应第三行
            for (int i = 0; i < list.size(); i++) {
                //单元格宽度自适应
                sheet.autoSizeColumn((short) 0);
                sheet.autoSizeColumn((short) 1);
                sheet.autoSizeColumn((short) 2);
                //从sheet第三行开始填充数据
                HSSFRow rowx = sheet.createRow(i + 2);
                Map<String, Object> map = result.get(i);
                //这里的hospitalid,idnumber等都是前面定义的全局变量
                String platformCode = (String) map.get("platformCode");
                HSSFCell cell00 = rowx.createCell(0);
                cell00.setCellStyle(style);
                cell00.setCellValue(platformCode);

                String platformType = (String) map.get("platformType");
                HSSFCell cell01 = rowx.createCell(1);
                cell01.setCellStyle(style);
                cell01.setCellValue(platformType);

                String agent = (String) map.get("agent");
                HSSFCell cell02 = rowx.createCell(2);
                cell02.setCellStyle(style);
                cell02.setCellValue(agent);

                String dialCodeType = (String) map.get("dialCodeType");
                HSSFCell cell03 = rowx.createCell(3);
                cell03.setCellStyle(style);
                cell03.setCellValue(dialCodeType);

                String createTime = (String) map.get("createTime");
                HSSFCell cell04 = rowx.createCell(4);
                cell04.setCellStyle(style);
                cell04.setCellValue(createTime);

                String createBy = (String) map.get("createBy");
                HSSFCell cell05 = rowx.createCell(5);
                cell05.setCellStyle(style);
                cell05.setCellValue(createBy);
            }
            //输出Excel文件
            OutputStream output = response.getOutputStream();
            response.reset();
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);//文件名这里可以改
            response.setContentType("application/msexcel");
            wb.write(output);
            output.close();

        } catch (Exception e) {
            log.error("PlatformController.export,导出台码信息, userId======" + userId + ", 异常======", e);
            e.printStackTrace();
        }

    }

    /**
     * 导出二维码
     */
    @RequestMapping(method = RequestMethod.POST, value = ("/v1.0/user/app/Platform/exportImg/{token}"))
    @ResponseBody
    public Object exportImg(@PathVariable("token") String token,
                            @RequestParam(value = "dialCode", required = false) String dialCode) {
        long userId = 0;
        List<Platform> list = new ArrayList<>();
        String path = "";
        try {
            userId = TokenUtil.getUserId(token);
            if (StringUtils.isNotBlank(dialCode)) {
                list = platformService.selectPlatform(dialCode);
            }
            if (!list.isEmpty()) {
                path = CompressUtil.zip(list, qrcodePath, qrcodePath, "");
            }
            return CommonsUtil.returnSuccess("http://xijingpay.com/upload/qrcode/temporary/" + path);
        } catch (Exception e) {
            log.error("PlatformController.exportImg,批量导出二维码, userId======" + userId + ", 异常======", e);
            return CommonsUtil.returnError("批量导出二维码失败！");
        }

    }


    /**
     * 绑定商户
     */
    @RequestMapping(method = RequestMethod.POST, value = ("/v1.0/user/app/Platform/binding/{token}"))
    @ResponseBody
    public Object bindingDialCode(@PathVariable("token") String token, @RequestParam(value = "type", required = false) String type,
                                  Platform platform, @RequestParam(value = "merchantId", required = false) String merchantId) {
        long userId = 0;
        try {
            userId = TokenUtil.getUserId(token);
            if (StringUtils.isBlank(platform.getPlatformCode() + "")) {
                return CommonsUtil.returnError("台卡号不能为空");
            }
            PlatformEntity entity = new PlatformEntity();
            entity.setPlatformCode(platform.getPlatformCode());
            List<Platform> list = platformService.queryPlatform(entity);

            if (list.isEmpty()) {
                return CommonsUtil.returnError(platform.getPlatformCode() + ", 该台卡号不存在!");
            } else {
                String state = "";
                String shopId = "";
                for (Platform enti : list) {
                    state = StringUtils.trimToEmpty(enti.getState());
                    shopId = StringUtils.trimToEmpty(enti.getShopId());
                }
                if ("1".equals(state)) {
                    if (!merchantId.equalsIgnoreCase(shopId)) {
                        return CommonsUtil.returnError("绑定失败, 该台卡已被绑定, 不能重复绑定！");
                    }
                } else if ("2".equals(state)) {
                    if (!merchantId.equalsIgnoreCase(shopId)) {
                        return CommonsUtil.returnError("激活失败，该台卡已被其他用户激活！");
                    }
                }
            }
            platform.setShopId(merchantId);
            ShopRegister shop = shopRegisterBussiness.findByMobilePhone(merchantId);
            if(shop == null){
                return CommonsUtil.returnError("该商户未注册，请确认！");
            }

            if (StringUtils.isBlank(shop.getShopName())) {
                return CommonsUtil.returnError("该商户未认证，请确认！");
            }
            if (shop.getStatus() != 5) {
                return CommonsUtil.returnError("该商户未审核，请确认！");
            }
            String introducerPhone = platform.getIntroducerPhone();
            if (StringUtils.isEmpty(introducerPhone)) {
                return CommonsUtil.returnError("请输入推广人手机号！");
            }
            if (!introducerPhone.matches("^1\\d{10}$")) {
                return CommonsUtil.returnError("推广人手机号码输入错误！");
            }
            if (type.equals("2")) {
                User user = userLoginRegisterBusiness.queryUserByPhone(merchantId);
                FastSilverPicPath picPath = fastSilverPicPathRepository.queryByUserId(user.getId());
                if (picPath == null) {
                    return CommonsUtil.returnError("该商户信息不完整，请上传图片");
                }
                Map<String,String>  pram = queryInternal(String.valueOf(user.getId()));

                String re = MapUtils.getString(pram,"result");
                if (re.equals("null")) {

                    UserBankInfo bankInfo = userBankInfoBusiness.findUserId(user.getId());
                    if (bankInfo == null) {
                        return CommonsUtil.returnError("该用户未绑定银行卡");
                    }

                    //同步注册快银通道
                    Map<String,String> map = syn( user.getId(),shop,picPath,bankInfo);
                    String respCode = MapUtils.getString(map,"resp_code");
                    if (!respCode.equals(CommonConstants.SUCCESS)) {
                        return CommonsUtil.returnError("商户激活和进件失败！");
                    }
                }
            }
            platform.setState(type);
            platform.setShopId(merchantId);
            platformService.updatePlatform(platform, "1");
            return CommonsUtil.returnSuccess(null);
        } catch (ServiceException e) {
            log.error("保存失败");
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            log.error("PlatformController.bindingDialCode,绑定商户或激活,userId====== " + userId + ", type = " + type + "异常======", e.getMessage());
            return CommonsUtil.returnError("绑定商户失败！");
        }
    }



    private Map<String,String> queryInternal(String userId) {

        Map<String,String> resultMap = new HashMap<>();
        /* 1、设置请求服务地址 */
        URI uri = util.getServiceUrl("channel", "error url request!");
        String url = uri + "/v1.0/channel/fast_silver/query/internal?userId="+userId;

        /* 3、创建连接 */
        String result = restTemplate.getForObject(url, String.class);
        /* 4、处理返回结果 */
        Map<String,String> pram = JSONObject.fromObject(result);
        return pram;

    }


    /**
     * 快银商户进件
     */
    @RequestMapping(method = RequestMethod.GET, value = ("/v1.0/user/app/Platform/incoming/{token}"))
    public @ResponseBody Object shopIncoming(@PathVariable("token") String token,
                               @RequestParam(value = "phone") String phone) {
        long userId = 0;
        try {
            userId = TokenUtil.getUserId(token);
            User user = userLoginRegisterBusiness.queryUserByPhone(phone);
            if (user == null) {
                return CommonsUtil.returnError("该商户不存在！");
            }
            ShopRegister shop = shopRegisterBussiness.findByUserId(user.getId());
            if (shop == null) {
                return CommonsUtil.returnError("该商户未做商户进件！");
            }
            FastSilverPicPath picPath = fastSilverPicPathRepository.queryByUserId(user.getId());
            if (picPath == null) {
                return CommonsUtil.returnError("该商户信息不完整，请做台卡激活");
            }
            UserBankInfo bankInfo = userBankInfoBusiness.findUserId(userId);
            if (bankInfo == null) {
                return CommonsUtil.returnError("该用户未绑定银行卡");
            }
            return syn(user.getId(),shop,picPath,bankInfo);
        } catch (Exception e) {
            log.error("商户进件异常,{}" + userId);
            return CommonsUtil.returnError("手动进件失败！");
        }
    }


    private Map<String,String>  syn(long userId,ShopRegister shop,FastSilverPicPath picPath,UserBankInfo bankInfo) {
        //获取微信支付宝费率
        List<ThirdPayRate> result = thirdPayRateBusiness.findThirdPayRate(shop.getBrandId());
        BigDecimal amount = new BigDecimal("300.00");
        BigDecimal weixin = BigDecimal.ZERO;
        BigDecimal alipay = BigDecimal.ZERO;
        for (ThirdPayRate thirdPayRate : result) {
            if (thirdPayRate.getType().getValue().equals(ThirdPayType.ALIPAY.getValue())) {
                alipay = thirdPayRate.getPayRate(amount);
            } else if (thirdPayRate.getType().getValue().equals(ThirdPayType.WECHAT.getValue())) {
                weixin = thirdPayRate.getPayRate(amount);
            }
        }
        User user = userLoginRegisterBusiness.getPreUserId(userId);
        if (bankInfo == null) {
            throw  new RuntimeException("该用户未绑定银行卡");
        }

        MultiValueMap<String, Object> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("userId",String.valueOf(shop.getUserId()));
        requestEntity.add("shopName",String.valueOf(shop.getShopName()));
        requestEntity.add("nickname",String.valueOf(shop.getShopShortName()));
        requestEntity.add("merchantName",String.valueOf(user.getFullname()));
        requestEntity.add("phone",String.valueOf(user.getPhone()));
        requestEntity.add("shopPhone",String.valueOf(shop.getShopCustomerPhone()));
        if (StringUtils.isBlank(user.getAddress())) {
            throw new RuntimeException("用户地址不能为空");
        }

        if (StringUtils.isBlank(user.getEmail())) {
            throw  new RuntimeException("用户邮箱不能为空");
        }

        requestEntity.add("shopAddress",shop.getShopAddress());
        requestEntity.add("email",user.getEmail());
        requestEntity.add("province",shop.getShopProvinces());
        requestEntity.add("city",shop.getShopCity());
        requestEntity.add("shopAreas",shop.getShopAreas());
        requestEntity.add("area",shop.getShopAreas());
        requestEntity.add("address",shop.getShopAddress());
        requestEntity.add("businessType",shop.getShopType());
        if (StringUtils.isNotBlank(shop.getShopIdNumber())) {
            requestEntity.add("licenceNo", shop.getShopIdNumber());
        } else {
            requestEntity.add("licenceNo", "");
        }

        requestEntity.add("licenceBeginDate",shop.getShopStartTime());
        requestEntity.add("licenceExpireDate",shop.getShopIdNumExTime());
        requestEntity.add("artifName",shop.getLegalName());
        requestEntity.add("artifPhone",shop.getShopUserPhone());
        requestEntity.add("idCard",shop.getLegalIdNumber());
        requestEntity.add("rateWx",String.valueOf(weixin));
        requestEntity.add("rateAlipay",String.valueOf(alipay));
        requestEntity.add("cardName",shop.getSettleAccountName());
        requestEntity.add("card",shop.getSettleAccountNumber());
        requestEntity.add("cardPhone",shop.getBankPhone());
        requestEntity.add("bankName",shop.getSettleBank());
        requestEntity.add("bankAddress",shop.getSettleBranchBank());
        requestEntity.add("bankAddNo",bankInfo.getLineNo());
        requestEntity.add("bankIdCard",shop.getLegalIdNumber());
        requestEntity.add("type",shop.getIndustryCategory());
        requestEntity.add("classify",shop.getIndustryCategory());
        Map<String,String> pram = new HashMap<>();
        pram.put("business",picPath.getBusiness());
        pram.put("businessCard",picPath.getBusinessCard());
        pram.put("identityBack",picPath.getIdentityBack());
        pram.put("identityBackCpoy",picPath.getIdentityBackCpoy());
        pram.put("identityBody",picPath.getIdentityBody());
        pram.put("identityFace",picPath.getIdentityFace());
        pram.put("identityFaceCopy",picPath.getIdentityFaceCopy());
        pram.put("merchantChech",picPath.getMerchantChech());
        pram.put("merchantHead",picPath.getMerchantHead());
        pram.put("otherPhotoFour",picPath.getOtherPhotoFour());
        pram.put("otherPhoto",picPath.getOtherPhoto());
        pram.put("otherPhotoThree",picPath.getOtherPhotoThree());
        pram.put("otherPhotoTwo",picPath.getOtherPhotoTwo());
        pram.put("cardFace",picPath.getBankFrontPhoto());
        requestEntity.add("fastSilverUpload",pram);
        return synFastSilver(requestEntity);
    }

    private Map<String,String> synFastSilver(MultiValueMap<String, Object> requestEntity) {

        Map<String,String> resultMap = new HashMap<>();
        /* 1、设置请求服务地址 */
        URI uri = util.getServiceUrl("channel", "error url request!");
        String url = uri + "/v1.0/channel/fast_silver/internal";
       // MultiValueMap<String, Object> entity = new LinkedMultiValueMap<>();
        /* 3、创建连接 */
        String result = restTemplate.postForObject(url, requestEntity, String.class);

        /* 4、处理返回结果 */
        resultMap = JSONObject.fromObject(result);
        return resultMap;
    }


    /**
     * 查询商户信息
     */
    @RequestMapping(method = RequestMethod.POST, value = ("/v1.0/user/app/Platform/shopName/{token}"))
    @ResponseBody
    public Object queryShopRegister(@PathVariable("token") String token, Platform platform) {
        long userId = 0;
        try {
            userId = TokenUtil.getUserId(token);
            return CommonsUtil.returnSuccess(shopRegisterBussiness.queryShopRegister(platform));
        } catch (Exception e) {
            log.error("PlatformController.queryShopRegister, 查询商户信息, userId======" + userId + ", 异常======" + e);
            return CommonsUtil.returnError("查询商户信息失败！");
        }
    }

    /**
     * 总后台更换当前台码的台码代理
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/Platform/bmsUpdatePlatForm/{token}")
    public @ResponseBody Object bmsUpdatePlatForm(@PathVariable(value = "token") String token,
                                                  @RequestParam(value = "fromAgent") String fromAgent,
                                                  @RequestParam(value = "toAgent") String toAgent) {
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return CommonsUtil.returnError("token无效！");
        }
        try {
            if (!fromAgent.matches("^1\\d{10}$") || !toAgent.matches("^1\\d{10}$")) {
                return CommonsUtil.returnError("手机号码填写错误！");
            }
            platformService.bmsUpdatePlatForm(fromAgent, toAgent);
            log.info("总后台更换当前台码的台码代理/v1.0/user/Platform/bmsUpdatePlatForm/{token}成功");
            return CommonsUtil.returnSuccess( "当前台码代理更换成功！");
        } catch (Exception e) {
            log.error("总后台更换当前台码代理/v1.0/user/Platform/bmsUpdatePlatForm/{token}异常");
            if (e.getMessage().contains("变更台码代理失败")) {
                return CommonsUtil.returnError(e.getMessage());
            }
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    /**
     * 根据代理商手机号查询后台扫码交易记录中的当前代理商下的交易记录
     */
    @PostMapping(value = "/v1.0/user/Platform/getUserIdByPlatform")
    public @ResponseBody Object getUserIdByPlatform(@RequestParam(value = "agent") String agent) {
        try {
            String userIds = platformService.getUserIdByPlatform(agent);
            Map<String, Object> res = new HashMap<>();
            res.put("userId", userIds);
            return CommonsUtil.returnSuccess(res, "获取userId成功！");
        } catch (Exception e) {
            if (e.getMessage().contains("获取")) {
                return CommonsUtil.returnError("获取userId失败！");
            }
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }
}
